<template>
    <scroll 
        class="suggest" 
        :data="result" 
        :pullup="pullup"
        @scrollToEnd="searchMore"
        ref="suggest"
        :beforeScroll="beforeScroll"
        @beforeScroll="listScroll"
    >
        <ul class="suggest-list">
            <li @click="selectItem(item)" class="suggest-item" v-for="(item, index) in result" :key="index">
                <div class="icon">
                    <i :class="getIconCls(item)"></i>
                </div>
                <div class="name">
                    <p class="text" v-html="getDisplayName(item)"></p>
                </div>
            </li>
            <loading v-show="hasMore" title=""></loading>
        </ul>
        <ul>
            <div v-show="!hasMore && !result.length" class="no-result-wrap">
                <no-result title="暂无搜索结果"></no-result>
            </div>
        </ul>
    </scroll>
</template>

<script>
import { getSearchSongList } from 'api/search'
import { ERR_OK } from 'api/config'
import { createSong } from 'common/js/song'
import Scroll from 'base/scroll/scroll'
import Loading from 'base/loading/loading'
import Singer from 'common/js/singer'
import { mapMutations, mapActions } from 'vuex'
import NoResult from 'base/no-result/no-result'

const SINGER = 'singer'

// 要搜索的歌曲条目为20
const PERPAGE = 20

export default {
    components: {
        Scroll,
        Loading,
        NoResult
    },
    props: {
        query: {
            type: String,
            default: ''
        },
        // 是否展示歌手
        showSinger: {
            type: Boolean,
            default: true
        }
    },
    watch: {
        // 检测到搜索关键词有变化则调用search函数
        query() {
            this.search()
        }
    },
    data() {
        return {
            page: 1,
            
            // 查询到的结果合集
            result: [],

            // 上拉刷新
            pullup: true,

            // 是否下拉还有数据
            hasMore: true,

            // 存放歌手信息
            singer: [],

            beforeScroll: true
        }
    },
    methods: {
        search() {
            // 重置操作
            this.page = 1
            this.hasMore = true
            this.$refs.suggest.scrollTo(0, 0)
            this.singer = []
            getSearchSongList(this.query, this.page, PERPAGE).then((res) => {
                if (res.data.code === ERR_OK) {
                    this.result = this._formatData(res.data.data)
                    this._checkMore(res.data.data)
                    console.log(this.result)
                }
            })
        },


        // 为搜索列表，根据歌手或歌曲显示不同的图标
        getIconCls(item) {
            if (item.type === SINGER) {
                return 'icon-mine'
            } else {
                return 'icon-music'
            }
        },

        // 处理搜索结果的文字显示方式
        getDisplayName(item) {
            if (item.type === SINGER) {
                return item.singerName
            } else {
                return `${item.name}  --  ${item.singer}`
            }
        },

        // 搜索更多
        searchMore() {
            if (!this.hasMore) {
                return
            }

            // 有上拉刷新行为则增加查询的页数，重新查询
            this.page ++ 
            getSearchSongList(this.query, this.page, PERPAGE).then((res) => {
                this.result = this.result.concat(this._formatData(res.data.data)) 
                this._checkMore(res.data.data)
            })
        },

        // 跳转到歌手或歌曲页面
        selectItem(item) {
            if (item.type === SINGER) {
                const singer = new Singer({
                    id: item.singerMID,
                    name: item.singerName
                })
                this.$router.push({
                    path: `/search/${singer.id}`
                })
                this.setSinger(singer)
            } else {
                this.insertSong(item)
            }

            // 派发select，给外部保存搜索历史
            this.$emit('select')
        },

        // 代理事件
        refresh() {
            this.$refs.suggest.refresh()
        },

        // 监听手机端上是否有滚动行为
        listScroll() {
            this.$emit('listScroll')
        },
        
        // 检查是否还有更多歌曲
        _checkMore(data) {
            let song = data.song
            if (!song.list.length || (song.curpage * PERPAGE + song.curnum) >= song.totalnum) {
                this.hasMore = false
            }
        },

        // 格式化歌曲数据
        _normalizeSongs(list) {
            let ret = []
            list.forEach(musicData => {
                if (musicData.songmid && musicData.songid) {
                    ret.push(createSong(musicData))
                }
            })
            return ret
        },

        // 格式化搜索到的结果
        _formatData(data) {
            // 存放数据
            let ret = []
            const zhida = data.zhida

            // 修复搜索结果重复出现歌手的bug
            if (zhida.zhida_singer && zhida.zhida_singer.singerID) {
                if (!this.singer.length) {
                    this.singer.push({...zhida.zhida_singer, ...{type: SINGER}})
                    ret = this.singer.concat(this._normalizeSongs(data.song.list))
                } else {
                    ret = ret.concat(this._normalizeSongs(data.song.list))
                }
            } 
            if (data.song) {
                ret = ret.concat(this._normalizeSongs(data.song.list))
            }
            return ret
        },

        ...mapMutations({
            setSinger: 'SET_SINGER'
        }),

        ...mapActions([
            'insertSong'
        ])
    }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px
      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px
      .icon
        flex: 0 0 30px
        width: 30px
        [class^="icon-"]
          font-size: 14px
          color: $color-text-d
      .name
        flex: 1
        font-size: $font-size-medium
        color: $color-text-d
        overflow: hidden
        .text
          no-wrap()
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>